import os
from training.msg import GeneralMsg
from iop import BusinessOperation


class RestClientBo(BusinessOperation):
    
    def on_init(self):
        # 检查 SaveInTxtBo 的实例是否具有 filename 属性
        # 如果没有，将其设置为 'formation.txt' 作为默认值
        if not hasattr(self, 'filename'):
            self.filename = 'data.txt'
        # 检查 SaveInTxtBo 的实例是否具有 path 属性
        # 如果没有，将其设置为 '/irisdev/app/data/' 作为默认值
        if not hasattr(self, 'path'):
            self.path = '/irisdev/app/data/'
        # 是否有path
        if not os.path.exists(self.path):
            # 没有的话建立一个
            os.makedirs(self.path)
            
    def on_tear_down(self):
        
        return None
    
    def on_formation_request(self, request: FormationRequest):

        with open(os.path.join(self.path, self.filename), 'a') as self.file:
            self.file.write(f'{request.id};{request.BMI};{request.Smoker};{request.Age};{request.Sex}\n')
            # log the message
            self.log_info(f'FormationRequest {request.id} saved in {self.filename}')
        response = GeneralResponse()
        response.status = 'OK'
        return response